<!--
 * @Author: quit
 * @Date: 2021-11-16 17:49:05
 * @LastEditTime: 2021-12-14 11:49:22
 * @Descripttion: 用户管理
-->
<template>
  <div id="ProjectManagement-content">
    <div class="app-container">
      <el-card>
        <el-row class="row1">
          <el-divider content-position="left">{{ $t('divider.divider1') }}</el-divider>
          <div class="search">
            <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
              <el-form-item :label="'用户姓名'">
                <el-input v-model="searchFrom.username" :placeholder="$t('input.searchPlaceholder')" />
              </el-form-item>
              <el-form-item :label="'类型'">
                <el-input v-model="searchFrom.usertype" :placeholder="$t('input.searchPlaceholder')" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-zoom-in" @click="getUserList">{{ $t('button.search') }}</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-refresh-right" @click="refresh">{{ '重置' }}</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-row>
        <el-row>
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemsBtn">{{ '添加用户' }}</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button>
        </el-row>
        <el-row>
          <el-table ref="table" v-loading="loading" :data="tableData" :empty-text="$t('table.emptyText')" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" min-width="40" fixed="left" />
            <el-table-column prop="userid" label="ID" min-width="50" fixed="left" />
            <el-table-column prop="username" :label="$t('table.username')" min-width="80" fixed="left" />
            <el-table-column prop="usertype" :label="$t('table.type')" min-width="50" />
            <el-table-column prop="usertime" :label="'过期时间'" min-width="100" />
            <el-table-column prop="usertelphone" :label="$t('table.phone')" min-width="60" />
            <el-table-column prop="usermail" :label="$t('table.email')" min-width="120" />
            <el-table-column prop="wxcode" :label="'微信'" min-width="70" />
            <el-table-column prop="qqcode" :label="'QQ'" min-width="70" />
            <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="100">
              <template slot-scope="scope">
                <el-button type="warning" size="mini" @click="handleEdit(scope.row)">{{ $t('button.edit') }}</el-button>
                <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('button.delete') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="pages.page"
            :page-sizes="[1, 5, 10, 15]"
            :page-size="pages.size"
            layout="prev, pager, next, total, sizes, jumper"
            :total="pages.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 添加\编辑当前弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogAddVisible" width="55%" @close="dialogAddVisibleClose">
      <el-form ref="dialogFrom" :model="dialogFrom" label-width="100px" class="dialog-from">
        <el-row>
          <el-divider class="one" content-position="left">基本信息</el-divider>
          <el-col :span="11">
            <el-form-item label="用户名">
              <el-input v-model="dialogFrom.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名密码">
              <el-input v-model="dialogFrom.userpass" placeholder="请输入用户名密码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户类型">
              <el-select v-model="dialogFrom.usertype" placeholder="请选择用户类型" clearable>
                <el-option v-for="(item, index) in usertypeData" :key="index" :label="item.usertypename" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期时间">
              <el-date-picker v-model="dialogFrom.usertime" class="select-time" type="datetime" placeholder="选择日期时间" @change="selectTime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider class="two" content-position="left">个人信息</el-divider>
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户真实姓名">
              <el-input v-model="dialogFrom.userrealname" placeholder="用户真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指纹">
              <el-input v-model="dialogFrom.userfingerprint" placeholder="请输入指纹" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item class="compound" label="个人证件">
              <el-input v-model="dialogFrom.usercode" placeholder="请输入证件编号">
                <el-select slot="prepend" v-model="dialogFrom.userdocumenttype" placeholder="请选择证件类型">
                  <el-option v-for="(item, index) in userIdTypeData" :key="index" :label="item.typename" :value="item.id" />
                </el-select>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="联系电话">
              <el-input v-model="dialogFrom.usertelphone" placeholder="请输入电话号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="dialogFrom.usermail" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="QQ号">
              <el-input v-model="dialogFrom.qqcode" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="dialogFrom.wxcode" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="性别">
              <el-input v-model="dialogFrom.sex" placeholder="性别" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input v-model="dialogFrom.age" placeholder="年龄" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <!-- <el-form-item label="用户照片">
              <el-upload
                ref="upload"
                action="#"
                list-type="picture-card"
                :limit="1"
                :file-list="fileList"
                :class="{ disabled: fileComputed }"
                :on-change="handleUpload"
                :http-request="requestImg"
                :before-upload="befroeUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item> -->
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button v-if="dialogAddVisibleState === 0" type="primary" @click="sendAdditem">确 定</el-button>
        <el-button v-if="dialogAddVisibleState === 1" type="primary" @click="sendEditItem">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, getUserType, getIdCardInfoList, addUser, editUserInfo, deleteUserInfo } from '@/api/BmRequest'
import { parseTime } from '@/utils/index'

export default {
  components: {},
  data() {
    return {
      searchFrom: { username: null, usertype: null },
      loading: false,
      tableData: [],
      checkedArr: [],
      pages: { page: 1, size: 10, total: 0 },
      dialogTitle: null,
      dialogAddVisible: false,
      dialogAddVisibleState: null,
      dialogFrom: {
        userid: null,
        username: null,
        userpass: 'admin',
        usertime: null,
        usertype: null,
        usercode: null,
        usertelphone: null,
        usermail: null,
        qqcode: null,
        wxcode: null,
        userfingerprint: null,
        userphoto: null,
        userrealname: null,
        userdocumenttype: null,
        token: null
      },
      usertypeData: [],
      userIdTypeData: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  created() {
    this.getUserList()
    this.getUserType()
    this.getIdCardInfoList()
  }, // 生命周期 - 创建完成（可以访问当前this实例）
  mounted() {}, // 生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 获取用户列表
    async getUserList() {
      this.loading = true
      const obj = {
        usermanager: this.searchFrom,
        pages: {
          page: this.pages.page,
          size: this.pages.size
        }
      }
      try {
        const { data } = await getUserList(obj)
        this.tableData = data.records
        this.pages.page = data.current
        this.pages.size = data.size
        this.pages.total = data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    // 获取用户类型
    async getUserType() {
      const { data } = await getUserType()
      this.usertypeData = data
    },

    // 获取用户证件类型
    async getIdCardInfoList() {
      const { data } = await getIdCardInfoList()
      this.userIdTypeData = data
    },

    // 重置按钮
    refresh() {
      this.searchFrom = { username: null, usertype: null }
      this.pages = { page: 1, size: 10, total: 0 }
      this.getUserList()
    },

    // 表格多选事件
    async handleSelectionChange(val) {
      const arr = []
      val.forEach((item, i) => {
        arr.push(item.userid)
      })
      this.checkedArr = arr
    },

    // /* 新增项目图片钩子函数 */
    // // 选择图片事件(文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用)
    // handleUpload(file, fileList) {
    //   if (!this.fileList.some(item => item.uid === file.uid)) {
    //     this.fileList.push(file)
    //   }
    // },
    // // 上传校验
    // befroeUpload(file) {
    //   const fileType = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
    //   if (!fileType.some(item => item === file.type)) {
    //     this.$message.error('上传文件格式不正确')
    //     return false
    //   }
    //   const maxSize = 5 * 1024 * 1024
    //   if (file.size > maxSize) {
    //     this.$message.error('上传文件过大')
    //     return false
    //   }
    //   return true
    // },
    // // 上传
    // async requestImg(params) {
    //   if (params.file) {
    //     const formData = new FormData()
    //     formData.append('file', params.file)
    //     const { data } = await UploadImg(this.botData.id, formData)
    //     this.thatFileNmae = data
    //   }
    // },
    // // 图片预览
    // handlePreview(file) {
    //   console.log(file.url)
    //   this.dialogPreviewVisible = true
    //   this.dialogImageUrl = file.url
    // },
    // // 删除当前图片
    // async handleRemove(file, fileList) {
    //   this.fileList = this.fileList.filter(item => {
    //     item.uid === file.uid
    //   })
    //   const res = await deteleImg(this.thatFileNmae, this.botData.id)
    //   console.log(res)
    // },

    // 添加按钮
    addItemsBtn() {
      this.dialogAddVisibleState = 0
      this.dialogTitle = '添加用户'
      this.dialogAddVisible = true
    },

    // 批量删除
    batchRemove() {
      if (this.checkedArr.length > 0) {
        this.$confirm('此操作将删除所选项目, 是否继续?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            if (this.checkedArr.length === this.tableData.length) {
              if (this.pages.page > 1) {
                this.pages.page--
              } else {
                this.pages.page = 1
              }
            }
            const { message } = await deleteUserInfo(this.checkedArr)
            await this.getUserList()
            this.$message.success({ message })
          })
          .catch(error => {
            console.log(error)
            this.$refs.tabel.clearSelection()
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },

    /* 弹出层事件 */
    // 关闭事件
    dialogAddVisibleClose() {
      this.dialogAddVisibleState = null
      this.dialogTitle = null
      this.dialogFrom = {
        userid: null,
        username: null,
        userpass: 'admin',
        usertime: null,
        usertype: null,
        usercode: null,
        usertelphone: null,
        usermail: null,
        qqcode: null,
        wxcode: null,
        userfingerprint: null,
        userphoto: null,
        userrealname: null,
        userdocumenttype: null,
        token: null
      }
    },
    // 时间选择
    selectTime(time) {
      const newDate = parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
      this.dialogFrom.usertime = newDate
    },
    // 确定
    async sendAdditem() {
      try {
        const { message } = await addUser(this.dialogFrom)
        this.dialogAddVisible = false
        await this.getUserList()
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      }
    },
    // 提交
    async sendEditItem() {
      try {
        const { message } = await editUserInfo(this.dialogFrom)
        this.dialogAddVisible = false
        await this.getUserList()
        this.$message.success({ message })
      } catch (error) {
        console.log(error)
      }
    },

    /* table-item 操作 */
    // 编辑
    handleEdit(data) {
      this.dialogFrom = { ...data }
      this.dialogAddVisibleState = 1
      this.dialogTitle = '编辑用户信息'
      this.dialogAddVisible = true
    },
    // 删除
    handleDelete(data) {
      this.$confirm('此操作将删除当前项目, 是否继续?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const Arr = [data.userid]
          const { message } = await deleteUserInfo(Arr)
          if (this.tableData.length === 1) {
            if (this.pages.page > 1) {
              this.pages.page--
            } else {
              this.pages.page = 1
            }
          }
          await this.getUserList()
          this.$message.success({ message })
        })
        .catch(error => {
          console.log(error)
        })
    },
    /* 分页操作 */
    // 分页当前页切换
    async handleCurrentChange(newPage) {
      this.pages.page = newPage
      await this.getUserList()
    },
    // 分页显示条数切换
    async handleSizeChange(newSize) {
      this.pages.size = newSize
      await this.getUserList()
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 10px;
}
.el-form {
  margin-left: 20px;
}
.el-input {
  width: 300px;
}
</style>

<style lang="scss" scoped>
::v-deep .el-input-group__append,
.el-input-group__prepend {
  background-color: #fff;
}
.row1 {
  margin-bottom: 10px;
  .search {
    border: 1px solid #dcdfe6;
    border-top: none;
    padding: 34px 10px 10px 10px;
    margin-top: -14px;
  }
}
.dialog-from {
  .el-input,
  .el-select {
    width: calc(100% - 10px);
  }
  .compound {
    .el-select {
      width: 165px;
    }
  }
  .one {
    .el-divider__text {
      padding: 2px 20px;
      background-color: #1a73e8;
      color: #f9f9f9;
    }
  }
  .two {
    .el-divider__text {
      padding: 2px 20px;
      background-color: #54b94b;
      color: #f9f9f9;
    }
  }
}
</style>
